package com.customization.unionpay.market.workflowaction;

import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.ClearFundButtonRelated;
import com.customization.unionpay.market.util.DailyReportRelated;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.PropUtils;
import org.apache.commons.lang.StringUtils;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.util.Map;

/**
 * @author sjm
 * @description 异常转正节点action
 */
public class MarketingErrorChangeAction implements Action {

    private static final Logger log = LoggerFactory.getLogger(MarketingErrorChangeAction.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        log.info("异常转正节点action！");
        RequestManager rm = requestInfo.getRequestManager();
        try {
            // # 营销事项申请流程id
            String marketingApplicationWorkId = com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_application_work_id");

            // 营销活动日报表台账表单id
            int reportFormId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_daily_report_form_id"));

            // 营销活动事项台账表单id
            int ledgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));

            // 查询枚举 日报流水类型 正常数据
            String rblslxNormalData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "正常数据");
            log.info("正常数据枚举值："+rblslxNormalData);
            // 查询枚举 日报流水类型 异常数据
            String rblslxErrorData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "异常数据");
            log.info("异常数据枚举值："+rblslxErrorData);
            // 查询枚举 日报流水类型 异常数据
            String rblslxEndData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "活动结束后交易数据");
            log.info("活动结束后交易数据枚举值："+rblslxEndData);

            String marketingActivityLedgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(ledgerFormId);
            log.info("marketingActivityLedgerTableName："+marketingActivityLedgerTableName);
            String reportTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(reportFormId);
            log.info("reportTableName："+reportTableName);

            // 流程表单id
            int formId = rm.getFormid();

            String errorChangeValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "ywlx", "异常转正");
            log.info("异常转正枚举值："+errorChangeValue);

            Map<String, Object> allFormData = com.customization.unionpay.market.util.FormDataUtils.getAllFormData(requestInfo);

            Map<String, String> mainMap = (Map<String, String>) allFormData.get("mainMap");
            // 所有明细表的值
            Map<String, Map<String, Map<String, String>>> detailMap = (Map<String, Map<String, Map<String, String>>>) allFormData.get("detailMap");

            // 主 业务类型        ywlx
            String ywlx = mainMap.get("ywlx");
            log.info("业务类型："+ywlx);

            if(errorChangeValue.equals(ywlx)){
                if (StringUtils.isNotBlank(marketingActivityLedgerTableName)) {
                    // 调增正数
                    Map<String, Map<String, String>> dt1 = detailMap.get("dt1");
                    for (String key : dt1.keySet()) {
                        String rblslxReal = rblslxNormalData;
                        String reson = "";
    
                        Map<String, String> value = dt1.get(key);
                        String yxpthdsqm = value.get("yxpthdsqm");
                        String hdjsbs = value.get("hdjsbs");
                        String qsje = StringUtils.isNotBlank(value.get("qsje")) ? value.get("qsje") : "0";
    
                        Double qsjeDb = Double.parseDouble(qsje);
                        if (StringUtils.isNotBlank(yxpthdsqm)) {
                            JSONObject marketingApplicantInfoByCode = com.customization.unionpay.market.util.ClearFundButtonRelated.getMarketingApplicantInfoByCode(marketingApplicationWorkId, marketingActivityLedgerTableName, yxpthdsqm);
                            log.info("获取营销事项申请单数据：" + marketingApplicantInfoByCode);
                            // ② 根据授权码(活动码)匹配财务系统对应SQ事项申请单，如果找不到该授权码对应SQ事项申请单，视为异常数据标记【日报流水类型】为“异常数据”;
                            if (marketingApplicantInfoByCode != null) {
                                String zjlyAp = marketingApplicantInfoByCode.getString("zjly");
                                String nbczjehj = marketingApplicantInfoByCode.getString("nbczjehj");
                                String cwsfjs = marketingApplicantInfoByCode.getString("cwsfjs");
                                String ysyje = marketingApplicantInfoByCode.getString("ysyje");
                                log.info("zjlyAp:"+zjlyAp);
                                log.info("cwsfjs:"+cwsfjs);
                                log.info("ysyje:"+ysyje);
                                log.info("hdjsbs:"+hdjsbs);
                                if (!"是".equals(hdjsbs)) {
                                    // ③ 如果找到对应SQ事项申请单，校验授权码尾号数字是否与申请单表头“资金来源”一致，如若不一致，视为异常数据标记【日报流水类型】为“异常数据”;
                                    boolean b = com.customization.unionpay.market.util.ClearFundButtonRelated.compareToAuthCode(yxpthdsqm, zjlyAp, marketingApplicationWorkId);
                                    log.info("b:"+b);
                                    if (!b) {
                                        rblslxReal = rblslxErrorData;
                                        reson = "授权码尾号数字与申请单表头资金来源不一致属于异常数据";
                                    }else {
                                        // ④ 如果对应SQ事项申请单“财务处理结束”为“是”，财务处理已结束，该行正数数据也视为异常数据标记【日报流水类型】为“异常数据”； 负数清算数据标记【日报流水类型】为“活动结束后交易数据”；
                                        if(cwsfjs != null && !"".equals(cwsfjs)){
                                            String cwsfjsName = FormDataUtils.getItemName(formId, "cwsfjs", cwsfjs);
                                            log.info("cwsfjsName:"+cwsfjsName);
                                            if ("是".equals(cwsfjsName)) {
                                                if (qsjeDb > 0) {
                                                    rblslxReal = rblslxErrorData;
                                                    reson = "SQ事项申请单财务处理结束为是，请款金额为正数属于异常数据";
                                                } else {
                                                    rblslxReal = rblslxEndData;
                                                    reson = "";
                                                }
                                                log.info("rblslxReal:"+rblslxReal);
                                            }else {
                                                String typeName = com.customization.unionpay.market.util.ClearFundButtonRelated.getTypeName(zjlyAp, marketingApplicationWorkId);
                                                log.info("typeName:"+typeName);
                                                if(ysyje != null && !"".equals(ysyje)){
                                                    Double hj = Double.valueOf(nbczjehj);
                                                    Double ysy = Double.valueOf(ysyje);
                                                    if ("内部营销".equals(typeName)) {
                                                        // ⑤ 如果对应SQ事项申请单“资金来源”为“内部”，“预算授权码”累计已使用金额大于对应SQ事项申请单“内部出资金额”；如超出，本次数据视为标记【日报流水类型】为“异常数据”；
                                                        if (ysy > hj) {
                                                            rblslxReal = rblslxErrorData;
                                                            reson = "SQ事项申请单资金来源为内部，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                        }
                                                    } else if ("内外部联合营销".equals(typeName)) {
                                                        // ⑥ 如果对应SQ事项申请单“资金来源”为“内外部联合”，且累计已使用金额大于SQ事项申请单“内部出资金额”，视为异常数据标记【日报流水类型】为“异常数据”，则该行数据只允许导入和确认，不能入账。（临界值：按剩余内部出资金额入账）
                                                        if (ysy > hj) {
                                                            rblslxReal = rblslxErrorData;
                                                            reson = "SQ事项申请单资金来源为资金来源，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                        }
                                                    }
                                                }
                                            }
                                        }else {
                                            String typeName = ClearFundButtonRelated.getTypeName(zjlyAp, marketingApplicationWorkId);
                                            log.info("typeName:"+typeName);
                                            if(ysyje != null && !"".equals(ysyje)){
                                                Double hj = Double.valueOf(nbczjehj);
                                                Double ysy = Double.valueOf(ysyje);
                                                if ("内部营销".equals(typeName)) {
                                                    // ⑤ 如果对应SQ事项申请单“资金来源”为“内部”，“预算授权码”累计已使用金额大于对应SQ事项申请单“内部出资金额”；如超出，本次数据视为标记【日报流水类型】为“异常数据”；
                                                    if (ysy > hj) {
                                                        rblslxReal = rblslxErrorData;
                                                        reson = "SQ事项申请单资金来源为内部，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                    }
                                                } else if ("内外部联合营销".equals(typeName)) {
                                                    // ⑥ 如果对应SQ事项申请单“资金来源”为“内外部联合”，且累计已使用金额大于SQ事项申请单“内部出资金额”，视为异常数据标记【日报流水类型】为“异常数据”，则该行数据只允许导入和确认，不能入账。（临界值：按剩余内部出资金额入账）
                                                    if (ysy > hj) {
                                                        rblslxReal = rblslxErrorData;
                                                        reson = "SQ事项申请单资金来源为资金来源，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    log.info("rblslxReal:"+rblslxReal);
                                    com.customization.unionpay.market.util.DailyReportRelated.updateStateAndYcxx(yxpthdsqm,reportTableName, rblslxReal,reson);
                                } else {
                                    // ① 若活动已结束，本次获取数据都视为活动结束后交易数据，其中正数标记【日报流水类型】为“异常数据”，负数标记【日报流水类型】为“活动结束后交易数据”；
                                    log.info("该条清算资金明细数据活动已结束");
                                    if (qsjeDb > 0) {
                                        rblslxReal = rblslxErrorData;
                                        reson = "SQ事项申请单活动结束标识为是，请款金额为正数属于异常数据";
                                    } else {
                                        rblslxReal = rblslxEndData;
                                        reson = "";
                                    }
                                    log.info("rblslxReal:"+rblslxReal);
                                    com.customization.unionpay.market.util.DailyReportRelated.updateStateAndYcxx(yxpthdsqm,reportTableName, rblslxReal,reson);
                                }
                            } else {
                                rblslxReal = rblslxErrorData;
                                log.info("rblslxReal:"+rblslxReal);
                                reson = "找不到该授权码对应SQ事项申请单";
                                DailyReportRelated.updateStateAndYcxx(yxpthdsqm,reportTableName, rblslxReal,reson);
                            }
                        } else {
                            log.error("授权码为空!");
                        }
                    }
                } else {
                    log.error("营销活动事项台账表名为空！");
                    // 异常报错是填写异常信息，阻止流程继续流转
                    requestInfo.getRequestManager().setMessageid("10001");
                    requestInfo.getRequestManager().setMessagecontent("营销活动事项台账表名为空");
                    return Action.FAILURE_AND_CONTINUE;
                }
            }else {
                log.info("当前不是异常转正，不做处理");
            }
        } catch (Exception e) {
            // 异常报错是填写异常信息，阻止流程继续流转
            requestInfo.getRequestManager().setMessageid("10001");
            requestInfo.getRequestManager().setMessagecontent(e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

}
